import { ref, type Ref, onMounted } from "vue";
import { requestBannerList } from "@/api/banner";
import { requestProductList } from "@/api/product";
import type { IProduct } from "@/type/types";
import { useRouter } from "vue-router";
// 获取banner列表
export const useBanner = () => {
  interface IBanner {
    id: number;
    url: string;
    content: string;
    number: number;
  }
  let bannerList: Ref<Array<IBanner>> = ref([]);
  const getBannerList = async () => {
    let data = await requestBannerList();
    const { resultCode, resultInfo } = data;
    if (resultCode == 1) {
      bannerList.value = resultInfo.list;
    }
  };
  onMounted(() => {
    getBannerList();
  });
  return {
    bannerList,
  };
};
// 获取商品列表
export const useProductList = () => {
  let productList: Ref<Array<IProduct>> = ref([]);
  const loading = ref(false);
  const finished = ref(false);
  const refreshing = ref(false);
  let currpageNo: number = 1;

  const getProductList = async (pageNo: number, pageSize: number) => {
    let data = await requestProductList(pageNo, pageSize);
    const { resultCode, resultInfo } = data;
    if (resultCode == 1) {
      productList.value = productList.value.concat(resultInfo.list);
    }
    loading.value = false;
    if (resultCode == -1) {
      finished.value = true;
    }
  };
  const onLoad = () => {
    if (refreshing.value) {
      productList.value = [];
      refreshing.value = false;
      currpageNo = 1;
    }
    getProductList(currpageNo++, 10);
  };

  const onRefresh = () => {
    // 清空列表数据
    finished.value = false;

    // 重新加载数据
    // 将 loading 设置为 true，表示处于加载状态
    loading.value = true;
    onLoad();
  };
  return {
    onRefresh,
    onLoad,
    refreshing,
    loading,
    finished,
    productList,
  };
};
// 商品详情
export const useProductDetail = () => {
  const router = useRouter();
  const onDetail = (id: number) => {
    router.push({ path: "/detail/" + id });
  };
  return { onDetail };
};
